package com.bulletelc.apollopre.module.main.center.setting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.framework.BaseActivity;
import com.bulletelc.apollopre.utils.EncryptUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.RegExUtil;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by CX on 2018/1/18.
 */

public class SmsVerifyActivity extends BaseActivity implements View.OnClickListener, FoolBar.ClickCallback{

    // views
    private Button btnAuthCode, btnStep;
    private EditText etPhone, etAuthCode;
    private FoolBar foolBar;

    // data
    private String authCode = "";
    private String userPhone = "";
    private String signatureData = "";

    @Override
    public int getLayoutRes() {
        return R.layout.sms_verify_activity;
    }

    @Override
    public void assignViews() {
        foolBar = findViewById(R.id.flBar);
        foolBar.setTitle(this.getResources().getString(R.string.sms_verify));
        etPhone = findViewById(R.id.et_phone);
        btnStep = findViewById(R.id.btn_step);
        etAuthCode = findViewById(R.id.et_auth_code);
        btnAuthCode = findViewById(R.id.btn_send_sms);
    }

    @Override
    public void setListener() {
        btnAuthCode.setOnClickListener(this);
        btnStep.setOnClickListener(this);
        foolBar.setClickCallback(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // 如果从个人中心过来的就设置手机号
        if (getIntent().getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_MOBILE || getIntent().getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_PASSWORD) {
            String mobileNum = SharedPreferencesUtil.getString(this, SPKey.SP_USER_MOBILE_NUMBER);
            etPhone.setText(MyUtil.getConcealMobileNum(mobileNum));
            userPhone = mobileNum;
            etPhone.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send_sms:
                // 获取超全局手机号码
                if (getIntent().getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_MOBILE ||getIntent().getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_PASSWORD) {
                    sendSms(userPhone);
                } else {
                    String mobile = etPhone.getText().toString().trim();
                    sendSms(mobile);
                }
                break;
            case R.id.btn_step:
                nextStep();
                break;
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 跳转
     * 传递手机号码要用全局，预防修改手机号码后传递
     */
    private void nextStep() {
        String etCode = etAuthCode.getText().toString().trim();
        if(etCode.equals("") || !etCode.equals(authCode)) {
            Toast.makeText(this, getString(R.string.hint_input_correct_auth_code) , Toast.LENGTH_LONG).show();
            return;
        }
        if (!"".equals(etCode) && etCode.equals(authCode) ) {
            Intent intent = getIntent();
            if (intent != null) {
                if(intent.getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_MOBILE) {
                    startActivity(new Intent(getApplicationContext(), ModifyMobileActivity.class));
                    this.finish();
                } else if (intent.getIntExtra(IntentCode.EXTRA_KEY_SETTING_ACTION, 0) == GlobalConfig.MSM_ACTION_MODIFY_PASSWORD){
                    startActivity(new Intent(getApplicationContext(), ModifyPasswordActivity.class));
                    this.finish();
                } else {
                    Intent intentForget = new Intent(getApplicationContext(), ModifyPasswordActivity.class);
                    intentForget.putExtra("signature_encrypt_data", signatureData);
                    intentForget.putExtra("mobile_number", userPhone);
                    startActivity(intentForget);
                    this.finish();
                }
            }

        } else {
            Toast.makeText(this, getString(R.string.hint_input_correct_auth_code), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 发送短信
     * @param mobile
     */
    private void sendSms(String mobile) {
        if (!RegExUtil.isMobileSimple(mobile)) {
            ToastUtil.showShortToast(this, getString(R.string.hint_input_correct_mobile));
            return;
        }
        getAuthCode(mobile);
        btnAuthCode.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=90;i>=0;i--) {
                    final int finalI = i;
                    btnAuthCode.post(new Runnable() {
                        @Override
                        public void run() {
                            btnAuthCode.setText(finalI+"s");
                        }
                    });
                    if (i==0) {
                        btnAuthCode.post(new Runnable() {
                            @Override
                            public void run() {
                                btnAuthCode.setEnabled(true);
                                btnAuthCode.setText(R.string.btn_send_again);
                            }
                        });
                    }
                    try {
                        Thread.sleep(999);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();
    }

    /**
     * 解析短信结果
     * @param mobile_number
     */
    public void getAuthCode(final String mobile_number) {
        JSONObject object = new JSONObject();
        JSONObject objSub = new JSONObject();
        try {
            objSub.put("mobile_number", mobile_number);
            objSub.put("signature_encrypt_data", EncryptUtil.sha256(mobile_number));
            object.put("CaptchaForm", objSub);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String objStr = object.toString();
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON),objStr);
        OkGo.<String>post(NetWorkPath.POST_SMS_CAPTCHA)
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseResultSMS(response, mobile_number);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 解析成功返回的数据  SMS
     *
     * @param response
     */
    private void parseResultSMS(Response<String> response, String mobileNum) {
        try {
            org.json.JSONObject obj = new org.json.JSONObject(response.body().toString());
            org.json.JSONObject meta = (org.json.JSONObject) obj.get("meta");
            org.json.JSONObject data = (org.json.JSONObject) obj.get("data");
            String code= (String) meta.get("code");
            if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                authCode = (String) data.get("code");
                signatureData = data.getString("signature_encrypt_data");
                // 确定收到短信，手机保存全局
                userPhone = mobileNum;
                Toast.makeText(this, getString(R.string.toast_send_sms_success), Toast.LENGTH_SHORT).show();
                //LogUtil.i(authCode);
            }else {
                Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
